<?php


namespace app\admin\controller;


use app\common\controller\AdminController;
use app\model\Config as ConfigModel;
use think\App;

/**
 * Class Config
 * @package app\product\controller
 * @ControllerAnnotation(title="配置管理")
 */
class Config extends AdminController
{

    public ?ConfigModel $model = null;

    public function __construct(App $app)
    {
        $this->model = new ConfigModel();
        parent::__construct($app);
    }

    /**
     * @NodeAnotation(title="配置列表")
     */
    public function configList() {
        $rows = $this->model->select()->toArray();
        $rows = array_format_key($rows, 'key');
        $list = [];
        foreach (ConfigModel::$list as $key => $val) {
            $list[] = [
                'key'=> $key,
                'title'=> $val[0],
                'value'=> $rows[$key]['value'] ?? $val[1],
                'update_at'=> $rows[$key]['update_at'] ?? '',
            ];
        }

        $res = [
            'list'=> $list,
        ];
        $this->success($res);
    }

    /**
     * @NodeAnotation(title="修改配置")
     */
    public function configEdit() {
        $data['key'] = input('key', '', 'trim');
        $data['value'] = input('value', '', 'trim');

        if (!isset(ConfigModel::$list[$data['key']])) {
            $this->error('KEY不合法');
        }

        $id = $this->model->where('key', $data['key'])->value('id');
        if ($id) {
            $this->model->where('id', $id)->update($data);
        } else {
            $data['title'] = ConfigModel::$list[$data['key']][0];
            $this->model->insert($data);
        }

        //刷新缓存
        $this->model->refreshCache();

        $this->success([],'保存成功');
    }
}